#include "detectionwindow.h"
#include "homepage.h"
#include "ui_detectionwindow.h"
#include "databasewindow.h"

DetectionWindow::DetectionWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DetectionWindow)
{
    ui->setupUi(this);
    initWindow();

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &DetectionWindow::updateData);
    timer->start(5000);
}

int DetectionWindow::AQIvalue = 0;
DetectionWindow::~DetectionWindow()
{
    delete ui;
}

void DetectionWindow::initWindow()
{

    aqiCenterWidget = new AqiCenterWidget(this);
    aqiCenterWidget->setFixedSize(200, 200); // 设置固定大小为圆形直径
    aqiCenterWidget->move((width() - 200) / 2, 50); // 根据主窗口宽度居中放置，距离顶部50像素

    QHBoxLayout *mainLayout = new QHBoxLayout(this);//主窗口布局
    // 创建QFrame容器,实时检测模块
    QFrame *Frame = new QFrame(this);
    Frame->setFrameShape(QFrame::Box);
    Frame->setFrameShadow(QFrame::Plain);
    Frame->setLineWidth(1);
    QHBoxLayout *frameLayout = new QHBoxLayout(Frame);
    //Frame->setFixedSize(1200,1200);
    
    // 创建QFrame容器,折线图模块
    QFrame *Frame0 = new QFrame(this);
    Frame0->setFrameShape(QFrame::Box);
    Frame0->setFrameShadow(QFrame::Plain);
    Frame0->setLineWidth(1);
    QHBoxLayout *frameLayout0 = new QHBoxLayout(Frame0);
    QVBoxLayout *detectionLayout = new QVBoxLayout;
    
    detectionLayout->addWidget(Frame);
    detectionLayout->addWidget(Frame0);
    detectionLayout->setStretchFactor(Frame,3);
    detectionLayout->setStretchFactor(Frame0,2);

    // 创建QFrame容器,本月达标天数模块
    QFrame *Frame1 = new QFrame(this);
    Frame1->setFrameShape(QFrame::Box);
    Frame1->setFrameShadow(QFrame::Plain);
    Frame1->setLineWidth(1);
    QHBoxLayout *frameLayout1 = new QHBoxLayout(Frame1);

    // 创建QFrame容器,年度达标天数模块
    QFrame *Frame2 = new QFrame(this);
    Frame2->setFrameShape(QFrame::Box);
    Frame2->setFrameShadow(QFrame::Plain);
    Frame2->setLineWidth(1);
    QHBoxLayout *frameLayout2 = new QHBoxLayout(Frame2);
    QVBoxLayout *standardLayout = new QVBoxLayout; //达标模块布局

    standardLayout->addWidget(Frame1);
    standardLayout->addWidget(Frame2);
    
    // 创建QFrame容器,用电量模块
    QFrame *Frame3 = new QFrame(this);
    Frame3->setFrameShape(QFrame::Box);
    Frame3->setFrameShadow(QFrame::Plain);
    Frame3->setLineWidth(1);
    QHBoxLayout *frameLayout3 = new QHBoxLayout(Frame3);
    
    // 创建QFrame容器,用水量模块
    QFrame *Frame4 = new QFrame(this);
    Frame4->setFrameShape(QFrame::Box);
    Frame4->setFrameShadow(QFrame::Plain);
    Frame4->setLineWidth(1);
    QHBoxLayout *frameLayout4 = new QHBoxLayout(Frame4);
    QVBoxLayout *useLayout = new QVBoxLayout;

    useLayout->addWidget(Frame3);
    useLayout->addWidget(Frame4);

    vLayout = new QVBoxLayout(Frame); //指标容器的布局
    QVBoxLayout *vLayout2 = new QVBoxLayout(Frame); //pm2.5和pm10的指标布局

// PM2.5 指标
    QWidget *pm25Widget = new QWidget(this);
    pm25Widget->setFixedSize(80, 80);
    pm25Widget->move(100, 300);
    QLabel *pm25IconLabel = new QLabel(pm25Widget);
    //pm25IconLabel->setPixmap(pm25Icon);
    pm25IconLabel->setAlignment(Qt::AlignCenter);
    pm25ValueLabel = new QLabel(pm25Widget);
    pm25ValueLabel->setText(QString::number(getPm25Value()));
    pm25ValueLabel->setFont(QFont("Arial", 14));
    pm25ValueLabel->setAlignment(Qt::AlignCenter);
    vLayout2->addWidget(pm25Widget);

    // PM10 指标
    QWidget *pm10Widget = new QWidget(this);
    pm10Widget->setFixedSize(80, 80);
    QLabel *pm10IconLabel = new QLabel(pm10Widget);
    //pm10IconLabel->setPixmap(pm10Icon);
    pm10IconLabel->setAlignment(Qt::AlignCenter);
    pm10ValueLabel = new QLabel(pm10Widget);
    pm10ValueLabel->setText(QString::number(getPm10Value()));
    pm10ValueLabel->setFont(QFont("Arial", 14));
    pm10ValueLabel->setAlignment(Qt::AlignCenter);
    vLayout2->addWidget(pm10Widget);

    // 气温指标
    QWidget *temperatureWidget = new QWidget;
    temperatureWidget->setFixedSize(120, 80);
    QVBoxLayout *temLayout = new QVBoxLayout;
    QHBoxLayout *temMainLayout = new QHBoxLayout(temperatureWidget);
    QPixmap temperatureIcon(":/new/prefix1/img/气温.png");
    QPixmap temPixmap =  temperatureIcon.scaled(60, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QLabel *temperatureIconLabel = new QLabel;
    QLabel *temperatureTextLabel = new QLabel;
    temperatureTextLabel->setText("温度");
    //QLabel#temperatureTextLabel {color: #55ffff;}
    temperatureTextLabel->setFont(QFont("楷体", 10));

    temperatureIconLabel->setPixmap(temPixmap);
    temperatureIconLabel->setAlignment(Qt::AlignLeft);
    temperatureValueLabel = new QLabel;
    temperatureValueLabel->setText(QString::number(getTemperatureValue()) + "℃");
    temperatureValueLabel->setFont(QFont("Arial", 10));
    temperatureValueLabel->setAlignment(Qt::AlignRight);

    temMainLayout->addWidget(temperatureIconLabel);
    temMainLayout->addLayout(temLayout);
    temLayout->addWidget(temperatureTextLabel);
    temLayout->addWidget(temperatureValueLabel);

    // 湿度指标
    QWidget *humidityWidget = new QWidget;
    humidityWidget->setFixedSize(120, 80);
    QVBoxLayout *humLayout = new QVBoxLayout;
    QHBoxLayout *humMainLayout = new QHBoxLayout(humidityWidget);
    humidityWidget->move(450, 300);
    QPixmap humidityIcon(":/new/prefix1/img/湿度.png");
    QPixmap humPixmap = humidityIcon.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QLabel *humidityIconLabel = new QLabel;
    QLabel *humidityTextLabel = new QLabel;
    humidityTextLabel->setText("湿度");
    humidityTextLabel->setFont(QFont("楷体", 10));

    humidityIconLabel->setPixmap(humPixmap);
    humidityIconLabel->setAlignment(Qt::AlignCenter);
    humidityValueLabel = new QLabel;
    humidityValueLabel->setText(QString::number(getHumidityValue()) + "%");
    humidityValueLabel->setFont(QFont("楷体", 10));
    humidityValueLabel->setAlignment(Qt::AlignRight);

    humMainLayout->addWidget(humidityIconLabel);
    humMainLayout->addLayout(humLayout);
    humLayout->addWidget(humidityTextLabel);
    humLayout->addWidget(humidityValueLabel);

    // 风速指标
    QWidget *windSpeedWidget = new QWidget;
    QVBoxLayout *windLayout = new QVBoxLayout;
    windSpeedWidget->setFixedSize(120, 80);
    QHBoxLayout *windMainLayout = new QHBoxLayout(windSpeedWidget);
    QPixmap windSpeedIcon(":/new/prefix1/img/风速.png");
    QPixmap scaledPixmap = windSpeedIcon.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QLabel *windSpeedIconLabel = new QLabel;
    QLabel *windSpeedTextLabel = new QLabel;
    windSpeedTextLabel->setText("风速");
    windSpeedTextLabel->setFont(QFont("楷体", 10));

    windSpeedIconLabel->setPixmap(scaledPixmap);
    windSpeedIconLabel->setAlignment(Qt::AlignCenter);
    windSpeedValueLabel = new QLabel;
    windSpeedValueLabel->setText(QString::number(getWindSpeedValue()) + "m/s");
    windSpeedValueLabel->setFont(QFont("楷体", 10));
    windSpeedValueLabel->setAlignment(Qt::AlignRight);
    windMainLayout->addWidget(windSpeedIconLabel);
    windMainLayout->addLayout(windLayout);
    windLayout->addWidget(windSpeedTextLabel);
    windLayout->addWidget(windSpeedValueLabel);

    //污水ph指标
    QWidget *phWidget = new QWidget;
    QVBoxLayout *phLayout = new QVBoxLayout;
    phWidget->setFixedSize(120, 80);
    QHBoxLayout *phMainLayout = new QHBoxLayout(phWidget);
    QPixmap phIcon(":/new/prefix1/img/污水ph值.png");
    QPixmap scaledPhPixmap = phIcon.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QLabel *phIconLabel = new QLabel;
    QLabel *phTextLabel = new QLabel;
    phTextLabel->setText("PH值");
    phTextLabel->setFont(QFont("楷体", 10));

    phIconLabel->setPixmap(scaledPhPixmap);
    phIconLabel->setAlignment(Qt::AlignCenter);
    phValueLabel = new QLabel;
    phValueLabel->setText(QString::number(getPHValue()));
    phValueLabel->setFont(QFont("楷体", 10));
    phValueLabel->setAlignment(Qt::AlignCenter);
    phMainLayout->addWidget(phIconLabel);
    phMainLayout->addLayout(phLayout);
    phLayout->addWidget(phTextLabel);
    phLayout->addWidget(phValueLabel);

    vLayout->addWidget(temperatureWidget);
    vLayout->addWidget(humidityWidget);
    vLayout->addWidget(windSpeedWidget);
    vLayout->addWidget(phWidget);

    frameLayout->addLayout(vLayout2);
    // 将aqiCenterWidget添加到frameLayout
    //创建重写的进度条
    //设置进度条的尺寸
    aqiCenterWidget->resize(200, 200);
    //显示进度条
    //progressBar.show();



    frameLayout->addWidget(aqiCenterWidget, 0, Qt::AlignCenter);
    frameLayout->addLayout(vLayout);

    mainLayout->addLayout(standardLayout);
    mainLayout->addLayout(detectionLayout);
    mainLayout->addLayout(useLayout);

    customPlot = new QCustomPlot;
    setupRealtimeDataDemo(customPlot);
    customPlot->replot();
    frameLayout0->addWidget(customPlot);

    //AQI饼图设计
    //chartView->deleteLater()
    // 创建 QChartview 对象
    chartView = new QChartView();
    chartView->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    chartView->setFixedSize(600,150);

    // 创建 QPieSeries 对象
    QPieSeries *series = new QPieSeries();
    series->setHoleSize(0.5); // 设置孔洞大小，可根据需要调整

    // 向饼图系列添加数据（这里仅为示例，你可以根据实际数据添加）
    series->append("Protein 4.2%", 4.2);
    series->append("Fat 15.6%", 15.6);
    series->append("Other 23.8%", 23.8);
    series->append("Carbs 56.4%", 56.4);

    // 将饼图系列添加到 QChart
    chartView->chart()->addSeries(series);

    // 设置图表标题
    chartView->chart()->setTitle("Donut with a lemon glaze (100g)");

    // 在饼图中央添加文本
    QFont font("楷体", 12); // 设置字体和字号
    QPainter painter;
    painter.begin(chartView->viewport());
    painter.setPen(Qt::white);
    painter.setFont(font);
    painter.drawText(chartView->chart()->plotArea().center(), "中央文本");
    painter.end();

    // 设置图表的其他属性（如主题、图例等，可根据需要设置）
    //chart->setTheme(QChart::ChartThemeDark);
    chartView->chart()->legend()->setAlignment(Qt::AlignRight);

    // 将 QChart 设置给 QChartView
    //chartView->setChart(chart);
    // 设置chartView在渲染图表时启用抗锯齿功能，这样图表的边缘等显示会更加平滑，
    // 视觉效果更加美观、细腻
    chartView->setRenderHint(QPainter::Antialiasing);
    frameLayout1->addWidget(chartView);


    customPlot1 = new QCustomPlot;
    setupBarChartDemo(customPlot1);
    customPlot1->replot();
    frameLayout3->addWidget(customPlot1);

    customPlot2 = new QCustomPlot;
    setupStyledDemo(customPlot2);
    customPlot2->replot();
    frameLayout4->addWidget(customPlot2);

}

int DetectionWindow::getPm25Value()
{
    static int pm25Value = 20;
    // 设置随机数种子，使用当前时间的毫秒部分
    qsrand(QTime::currentTime().msec());
    // 生成 0 到 10 之间的随机数
    int randomNumber = qrand() % 11;
    // 将范围从 0 到 10 映射到 -5 到 5
    int change = randomNumber - 5;
    pm25Value += change;
    if (pm25Value < 0)
    {
        pm25Value = 0;
    }
    else if (pm25Value > 50)
    {
        pm25Value = 50;
    }
    return pm25Value;
}

int DetectionWindow::getPm10Value()
{
    static int pm10Value = 30;
    // 设置随机数种子，使用当前时间的毫秒部分
    qsrand(QTime::currentTime().msec());
    // 生成 0 到 10 之间的随机数
    int randomNumber = qrand() % 11;
    // 将范围从 0 到 10 映射到 -5 到 5
    int change = randomNumber - 5;
    pm10Value += change;
    if (pm10Value < 0)
    {
        pm10Value = 0;
    }
    else if (pm10Value > 50)
    {
        pm10Value = 50;
    }
    return pm10Value;
}

int DetectionWindow::getTemperatureValue()
{
    static int temperatureValue = 25;
    // 设置随机数种子，使用当前时间的毫秒部分
    qsrand(QTime::currentTime().msec());
    // 生成 0 到 10 之间的随机数
    int randomNumber = qrand() % 11;
    // 将范围从 0 到 10 映射到 -5 到 5
    int change = randomNumber - 5;
    temperatureValue += change;
    if (temperatureValue < 0)
    {
        temperatureValue = 0;
    }
    else if (temperatureValue > 50)
    {
        temperatureValue = 50;
    }
    return temperatureValue;
}

int DetectionWindow::getHumidityValue()
{
    static int humidityValue = 50;
    // 设置随机数种子，使用当前时间的毫秒部分
    qsrand(QTime::currentTime().msec());
    // 生成 0 到 10 之间的随机数
    int randomNumber = qrand() % 11;
    // 将范围从 0 到 10 映射到 -5 到 5
    int change = randomNumber - 5;
    humidityValue += change;
    if (humidityValue < 0)
    {
        humidityValue = 0;
    }
    else if (humidityValue > 100)
    {
        humidityValue = 100;
    }
    return humidityValue;
}

int DetectionWindow::getWindSpeedValue()
{
    static int windSpeedValue = 5;
    qsrand(QTime::currentTime().msec());
    // 生成 0 到 5 之间的随机数
    int randomNumber = qrand() % 5;
    // 将范围从 0 到 10 映射到 -5 到 5
    int change = randomNumber - 2;
    windSpeedValue += change;
    if (windSpeedValue < 0)
    {
        windSpeedValue = 0;
    }
    else if (windSpeedValue > 18)
    {
        windSpeedValue = 18;
    }
    return windSpeedValue;
}

int DetectionWindow::getPHValue()
{
    static int PHValue = 5;
    qsrand(QTime::currentTime().msec());
    // 生成 0 到 10 之间的随机数
    int randomNumber = qrand() % 8;
    // 将范围从 0 到 10 映射到 -5 到 5
    int change = randomNumber - 3;
    PHValue += change;
    if (PHValue < 0)
    {
        PHValue = 0;
    }
    else if (PHValue > 10)
    {
        PHValue = 10;
    }
    return PHValue;
}

void DetectionWindow::updateData()
{
   pm25ValueLabel->setText(QString::number(getPm25Value()));
   pm10ValueLabel->setText(QString::number(getPm10Value()));
   temperatureValueLabel->setText(QString::number(getTemperatureValue()) + "℃");
   humidityValueLabel->setText(QString::number(getHumidityValue()) + "%");
   windSpeedValueLabel->setText(QString::number(getWindSpeedValue()) + "m/s");
   phValueLabel->setText(QString::number(getPHValue()));

  // aqiCenterWidget->update();
   //实例化QSqlQuery对象
   QSqlQuery query;

   int temperuature =  getTemperatureValue();
   int humidity = getHumidityValue();
   int wind = getWindSpeedValue();
   int PH = getPHValue();
   int PM25 = getPm25Value();
   int PM10 = getPm10Value();
   double maxSum = 50.0 + 50.0 + 50.0 + 100.0 + 18.0 + 10.0;
   AQIvalue = (temperuature + humidity + wind + PH + PM25 + PM10) / 6;

   aqiCenterWidget->setProgress(AQIvalue / maxSum);
   QDateTime curTime = QDateTime::currentDateTime();
   QString time = curTime.toString("yyyy-MM-dd HH:mm:ss");
   //准备Sql语句
   query.prepare("INSERT INTO data (\"检测时间\",\"温度(℃)\",\"湿度(%)\",\"风速(m/s)\",\"PH值\",\"PM2.5\",\"PM10\") VALUES (?,?,?,?,?,?,?)");
   query.bindValue(0,time);
   query.bindValue(1,temperuature);
   query.bindValue(2,humidity);
   query.bindValue(3,wind);
   query.bindValue(4,PH);
   query.bindValue(5,PM25);
   query.bindValue(6,PM10);

   //执行Sql语句
   if(!query.exec())
   {
       QMessageBox::warning(this,"SQL ERROR",query.lastError().text(),QMessageBox::Ok);
   }
}

void AqiCenterWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    //int side = qMin(width(), height());
    int outerRadius = 90;//设置外圆的半径尺寸大小
    //int innerRadius = outerRadius - 10;//半径

    //设置图案的中心点
    QPoint centre(width() / 2, height() / 2);

    // 外圆 第一个参数是外圆的轮廓颜色
    //QPen outerPen(QBrush(Qt::black), Qt::black, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
    QPen outerPen(Qt::black, 0.6);//设置外圆的轮廓颜色和宽度
    painter.setPen(outerPen);
    //设置外圆的位置和尺寸
    painter.drawEllipse(centre, outerRadius, outerRadius);

    // 创建从绿色到红色的线性渐变画刷
    QLinearGradient gradient(0, height() / 2 - outerRadius, 0, height() / 2 + outerRadius);
    gradient.setColorAt(0, Qt::green);
    gradient.setColorAt(1, Qt::red);


    // 进度弧线
    QPen progressPen(QBrush(Qt::green), Qt::blue, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
    progressPen.setWidth(0); // 设置没有轮廓
    QBrush brush(gradient);
    painter.setPen(progressPen);
    painter.setBrush(brush);

    // 根据进度计算起始和结束角度（注意：Qt的drawPie方法角度是16分之一度为单位）
    int startAngle = 90 * 16; // 从9点钟位置开始
    int spanAngle = int(-360 * 16 * m_progress); // 跨越的角度 负号是顺时针

    // 绘制饼状图的部分区域作为进度条
    // 从9点钟逆时针扫
    //drawPie定义饼状图起始和结束角度
    painter.drawPie(QRect(QPoint(width() / 2 - outerRadius, height() / 2 - outerRadius),//一个正方形定义进度圆的大小,设置位置
                          QSize(2 * outerRadius, 2 * outerRadius)),//设置矩形尺寸
                    startAngle, spanAngle);//弧线进度条的起始和跨越角度

    //再画一个圆尝试覆盖
    QPainter painter2(this);
    painter2.setRenderHint(QPainter::Antialiasing); // 开启抗锯齿，使边缘更平滑

    // 设置画笔（QPen）和画刷（QBrush）
    QPen pen2(Qt::black, 0.6); // 内圆外轮廓颜色与宽度
    QBrush brush2(Qt::green);  // 内圆填充
    painter2.setPen(pen2);
    painter2.setBrush(brush2);

    // 绘制圆形，参数为：矩形边界框（包含圆的矩形），从该矩形左上角开始的x和y偏移量，以及宽度和高度
    // 由于圆是椭圆的一种特殊情况，这里使用drawEllipse方法，并传递一个正方形作为边界框
    int radius = 50; // 圆的半径
    painter2.drawEllipse(centre, radius, radius); // 在窗口中心绘制圆
    //设置字体位置
    lab->move(width() / 2-19, height() / 2-50);
}

AqiCenterWidget::AqiCenterWidget(QWidget *parent):QWidget(parent), m_progress(0)
{
    //创建标签写上进度数字
    lab =new QLabel("0",this);
    QFont font;
    font.setPointSize(14); // 设置字体大小为20点
    // 将字体应用到QLabel上
    lab->setFont(font);
    lab->setFixedSize(QSize(100, 100));
}


//AQI值的饼图设计
void DetectionWindow::AqiPieChart()
{

}

//柱状图设计
void DetectionWindow::setupBarChartDemo(QCustomPlot *customPlot)
{
  demoName = "实时数据展示";
  // set dark background gradient:
  QLinearGradient gradient(0, 0, 0, 400);
  gradient.setColorAt(0, QColor(90, 90, 90));
  gradient.setColorAt(0.38, QColor(105, 105, 105));
  gradient.setColorAt(1, QColor(70, 70, 70));
  customPlot->setBackground(QBrush(gradient));
  customPlot->plotLayout()->insertRow(0);
  QCPTextElement *titleElement = new QCPTextElement(customPlot, "每日实时数据展示\ (平均值)", QFont("楷体", 12, QFont::Normal));
  titleElement->setTextColor(Qt::green);
  customPlot->plotLayout()->addElement(0, 0, titleElement);

  // create empty bar chart objects:
  QCPBars *regen = new QCPBars(customPlot->xAxis, customPlot->yAxis);
  QCPBars *nuclear = new QCPBars(customPlot->xAxis, customPlot->yAxis);
  QCPBars *fossil = new QCPBars(customPlot->xAxis, customPlot->yAxis);
  regen->setAntialiased(false); // gives more crisp, pixel aligned bar borders
  nuclear->setAntialiased(false);
  fossil->setAntialiased(false);
  regen->setStackingGap(1);
  nuclear->setStackingGap(1);
  fossil->setStackingGap(1);
  // set names and colors:
  fossil->setName("PM2.5");
  fossil->setPen(QPen(QColor(111, 9, 176).lighter(170)));
  fossil->setBrush(QColor(111, 9, 176));
  nuclear->setName("温度");
  nuclear->setPen(QPen(QColor(250, 170, 20).lighter(150)));
  nuclear->setBrush(QColor(250, 170, 20));
  regen->setName("PH值");
  regen->setPen(QPen(QColor(0, 168, 140).lighter(130)));
  regen->setBrush(QColor(0, 168, 140));
  // stack bars on top of each other:
  nuclear->moveAbove(fossil);
  regen->moveAbove(nuclear);

  // prepare x axis with country labels:
  QVector<double> ticks;
  QVector<QString> labels;
  ticks << 1 << 2 << 3 << 4 << 5 << 6 << 7;
  labels << "2025-01-12" << "2025-01-13" << "2025-01-14" << "2025-01-15" << "2025-01-16" << "2025-01-17" << "2025-01-18";
  QSharedPointer<QCPAxisTickerText> textTicker(new QCPAxisTickerText);
  textTicker->addTicks(ticks, labels);
  customPlot->xAxis->setTicker(textTicker);
  customPlot->xAxis->setTickLabelRotation(60);
  customPlot->xAxis->setSubTicks(false);
  customPlot->xAxis->setTickLength(0, 4);
  customPlot->xAxis->setRange(0, 8);
  customPlot->xAxis->setBasePen(QPen(Qt::white));
  customPlot->xAxis->setTickPen(QPen(Qt::white));
  customPlot->xAxis->grid()->setVisible(true);
  customPlot->xAxis->grid()->setPen(QPen(QColor(130, 130, 130), 0, Qt::DotLine));
  customPlot->xAxis->setTickLabelColor(Qt::white);
  customPlot->xAxis->setLabelColor(Qt::white);

  // prepare y axis:
  customPlot->yAxis->setRange(0, 12.1);
  customPlot->yAxis->setPadding(5); // a bit more space to the left border
  customPlot->yAxis->setBasePen(QPen(Qt::white));
  customPlot->yAxis->setTickPen(QPen(Qt::white));
  customPlot->yAxis->setSubTickPen(QPen(Qt::white));
  customPlot->yAxis->grid()->setSubGridVisible(true);
  customPlot->yAxis->setTickLabelColor(Qt::white);
  customPlot->yAxis->grid()->setPen(QPen(QColor(130, 130, 130), 0, Qt::SolidLine));
  customPlot->yAxis->grid()->setSubGridPen(QPen(QColor(130, 130, 130), 0, Qt::DotLine));

  // Add data:
  QVector<double> fossilData, nuclearData, regenData;
  fossilData  << 0.86*10.5 << 0.83*5.5 << 0.84*5.5 << 0.52*5.8 << 0.89*5.2 << 0.90*4.2 << 0.67*11.2;
  nuclearData << 0.08*10.5 << 0.12*5.5 << 0.12*5.5 << 0.40*5.8 << 0.09*5.2 << 0.00*4.2 << 0.07*11.2;
  regenData   << 0.06*10.5 << 0.05*5.5 << 0.04*5.5 << 0.06*5.8 << 0.02*5.2 << 0.07*4.2 << 0.05*11.2;
  fossil->setData(ticks, fossilData);
  nuclear->setData(ticks, nuclearData);
  regen->setData(ticks, regenData);

  // setup legend:
  customPlot->legend->setVisible(true);
  customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop|Qt::AlignHCenter);
  customPlot->legend->setBrush(QColor(255, 255, 255, 100));
  customPlot->legend->setBorderPen(Qt::NoPen);
  QFont legendFont = font();
  legendFont.setPointSize(10);
  customPlot->legend->setFont(legendFont);
  customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
}

//折线图设计
void DetectionWindow::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
  demoName = "Real Time Data Demo";

  // include this section to fully disable antialiasing for higher performance:

  customPlot->addGraph(); // blue line
  QPen bluePen(QColor(40, 110, 255));
  bluePen.setWidth(2);
  customPlot->graph(0)->setPen(bluePen);
  customPlot->addGraph(); // red line
  QPen redPen(QColor(255, 110, 40));
  redPen.setWidth(2);
  customPlot->graph(1)->setPen(redPen);
  QLinearGradient gradient(0, 0, 0, 400);
  gradient.setColorAt(0, QColor(90, 90, 90));
  gradient.setColorAt(0.38, QColor(105, 105, 105));
  gradient.setColorAt(1, QColor(70, 70, 70));
  customPlot->setBackground(QBrush(gradient));

  //设置图表标题
  customPlot->plotLayout()->insertRow(0);
  QCPTextElement *titleElement = new QCPTextElement(customPlot, "噪声/紫外线实时检测(间隔2s)", QFont("楷体", 12, QFont::Normal));
  titleElement->setTextColor(Qt::green);
  customPlot->plotLayout()->addElement(0, 0, titleElement);

  QSharedPointer<QCPAxisTickerDateTime> timeTicker(new QCPAxisTickerDateTime);
  timeTicker->setDateTimeFormat("HH:mm:ss");
  customPlot->xAxis->setTicker(timeTicker);
  customPlot->xAxis->setTickLabelColor(Qt::green);
  customPlot->yAxis->setTickLabelColor(Qt::green);
  customPlot->axisRect()->setupFullAxesBox();
  customPlot->yAxis->setRange(-1.2, 1.2);

  // make left and bottom axes transfer their ranges to right and top axes:
  connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
  connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

  // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
  connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
  dataTimer.start(0); // Interval 0 means to refresh as fast as possible
}

void DetectionWindow::realtimeDataSlot()
{
  QDateTime currentTime = QDateTime::currentDateTime();// 获取当前实时时间

  double key = currentTime.toMSecsSinceEpoch()/1000.0; // 转换为秒
  static double lastPointKey = 0;
  if (key-lastPointKey > 0.02) // at most add point every 2 ms
  {
    // add data to lines:
    customPlot->graph(0)->addData(key, qSin(key)+qrand()/(double)RAND_MAX*1*qSin(key/0.3843));
    customPlot->graph(1)->addData(key, qCos(key)+qrand()/(double)RAND_MAX*0.5*qSin(key/0.4364));
    // rescale value (vertical) axis to fit the current data:
    customPlot->graph(0)->rescaleValueAxis();
    customPlot->graph(1)->rescaleValueAxis(true);
    lastPointKey = key;
  }
  // make key axis range scroll with the data (at a constant range size of 8):
  customPlot->xAxis->setRange(key, 8, Qt::AlignRight);
  customPlot->replot();

  // calculate frames per second:
  static double lastFpsKey;
  static int frameCount;
  ++frameCount;
  if (key-lastFpsKey > 2) // average fps over 2 seconds
  {
    QStatusBar *statusBar = new QStatusBar;
    statusBar->showMessage(
          QString("%1 FPS, Total Data points: %2")
          .arg(frameCount/(key-lastFpsKey), 0, 'f', 0)
          .arg(customPlot->graph(0)->data()->size()+customPlot->graph(1)->data()->size())
          , 0);
    lastFpsKey = key;
    frameCount = 0;
  }
}
void DetectionWindow::setupStyledDemo(QCustomPlot *customPlot)
{
  demoName = "Styled Demo";

  // prepare data:
  QVector<double> x1(20), y1(20);
  QVector<double> x2(100), y2(100);
  QVector<double> x3(20), y3(20);
  QVector<double> x4(20), y4(20);
  for (int i=0; i<x1.size(); ++i)
  {
    x1[i] = i/(double)(x1.size()-1)*10;
    y1[i] = qCos(x1[i]*0.8+qSin(x1[i]*0.16+1.0))*qSin(x1[i]*0.54)+1.4;
  }
  for (int i=0; i<x2.size(); ++i)
  {
    x2[i] = i/(double)(x2.size()-1)*10;
    y2[i] = qCos(x2[i]*0.85+qSin(x2[i]*0.165+1.1))*qSin(x2[i]*0.50)+1.7;
  }
  for (int i=0; i<x3.size(); ++i)
  {
    x3[i] = i/(double)(x3.size()-1)*10;
    y3[i] = 0.05+3*(0.5+qCos(x3[i]*x3[i]*0.2+2)*0.5)/(double)(x3[i]+0.7)+qrand()/(double)RAND_MAX*0.01;
  }
  for (int i=0; i<x4.size(); ++i)
  {
    x4[i] = x3[i];
    y4[i] = (0.5-y3[i])+((x4[i]-2)*(x4[i]-2)*0.02);
  }

  // create and configure plottables:
  QCPGraph *graph1 = customPlot->addGraph();
  graph1->setData(x1, y1);
  graph1->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black, 1.5), QBrush(Qt::white), 9));
  graph1->setPen(QPen(QColor(120, 120, 120), 2));

  QCPGraph *graph2 = customPlot->addGraph();
  graph2->setData(x2, y2);
  graph2->setPen(Qt::NoPen);
  graph2->setBrush(QColor(200, 200, 200, 20));
  graph2->setChannelFillGraph(graph1);

  QCPBars *bars1 = new QCPBars(customPlot->xAxis, customPlot->yAxis);
  bars1->setWidth(9/(double)x3.size());
  bars1->setData(x3, y3);
  bars1->setPen(Qt::NoPen);
  bars1->setBrush(QColor(10, 140, 70, 160));

  QCPBars *bars2 = new QCPBars(customPlot->xAxis, customPlot->yAxis);
  bars2->setWidth(9/(double)x4.size());
  bars2->setData(x4, y4);
  bars2->setPen(Qt::NoPen);
  bars2->setBrush(QColor(10, 100, 50, 70));
  bars2->moveAbove(bars1);

  // move bars above graphs and grid below bars:
  customPlot->addLayer("abovemain", customPlot->layer("main"), QCustomPlot::limAbove);
  customPlot->addLayer("belowmain", customPlot->layer("main"), QCustomPlot::limBelow);
  graph1->setLayer("abovemain");
  customPlot->xAxis->grid()->setLayer("belowmain");
  customPlot->yAxis->grid()->setLayer("belowmain");

  // set some pens, brushes and backgrounds:
  customPlot->xAxis->setBasePen(QPen(Qt::white, 1));
  customPlot->yAxis->setBasePen(QPen(Qt::white, 1));
  customPlot->xAxis->setTickPen(QPen(Qt::white, 1));
  customPlot->yAxis->setTickPen(QPen(Qt::white, 1));
  customPlot->xAxis->setSubTickPen(QPen(Qt::white, 1));
  customPlot->yAxis->setSubTickPen(QPen(Qt::white, 1));
  customPlot->xAxis->setTickLabelColor(Qt::white);
  customPlot->yAxis->setTickLabelColor(Qt::white);
  customPlot->xAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
  customPlot->yAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
  customPlot->xAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
  customPlot->yAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
  customPlot->xAxis->grid()->setSubGridVisible(true);
  customPlot->yAxis->grid()->setSubGridVisible(true);
  customPlot->xAxis->grid()->setZeroLinePen(Qt::NoPen);
  customPlot->yAxis->grid()->setZeroLinePen(Qt::NoPen);
  customPlot->xAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
  customPlot->yAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
  QLinearGradient plotGradient;
  plotGradient.setStart(0, 0);
  plotGradient.setFinalStop(0, 350);
  plotGradient.setColorAt(0, QColor(80, 80, 80));
  plotGradient.setColorAt(1, QColor(50, 50, 50));
  customPlot->setBackground(plotGradient);
  QLinearGradient axisRectGradient;
  axisRectGradient.setStart(0, 0);
  axisRectGradient.setFinalStop(0, 350);
  axisRectGradient.setColorAt(0, QColor(80, 80, 80));
  axisRectGradient.setColorAt(1, QColor(30, 30, 30));
  customPlot->axisRect()->setBackground(axisRectGradient);

  customPlot->rescaleAxes();
  customPlot->yAxis->setRange(0, 2);
}

